﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using NLog;
using Quadrant.domain.Helpers;
using Quadrant.domain.Models;

namespace Quadrant.domain.Services
{
    public class StickServices : BaseServices
    {
        public StickServices(Logger logger) : base(logger) { }

        public Task<Stick[]> GetSticks(Guid userId, Guid? quadrantId = null)
        {
            var qry = this.DB.Sticks.AsNoTracking().Where(p => p.Quadrant.OwnerId == userId);
            if (quadrantId != null)
            {
                qry = qry.Where(p => p.QuadrantId == quadrantId.Value);
            }
            return qry.ToArrayAsync();
        }

        public Task<Stick> GetStick(long stickId)
        {
            return this.DB.Sticks.AsNoTracking().SingleAsync(p => p.Id == stickId);
        }

        public async Task<OpResult> SaveStick(Stick stick)
        {
            try
            {
                if (stick.Id == null)
                {
                    stick.Position = new BoardPosition();
                    this.DB.Sticks.Add(stick);
                }
                else
                {
                    var stickforPos = this.DB.Sticks.AsNoTracking().Single(p => p.Id == stick.Id);
                    stick.Position = stickforPos.Position;
                    this.DB.Entry(stick).State = EntityState.Modified;
                }
                await this.DB.SaveChangesAsync();
                return new OpResult { Id = stick.Id, Success = true };
            }
            catch (Exception ex)
            {
                this.Logger.Error("StickServices: " + ex.Message, ex);
                return new OpResult { Id = stick.Id, Success = false };
            }
        }

        public async Task<Boolean> SavePositionStick(long id, BoardPosition position)
        {
            try
            {
                var stick = await this.DB.Sticks.FindAsync(id);
                stick.Position = position;
                this.DB.Entry(stick).State = EntityState.Modified;

                return await this.DB.SaveChangesAsync() > 0;
            }
            catch (Exception ex)
            {
                this.Logger.Error("StickServices: " + ex.Message, ex);
                return false;
            }
        }

        public async Task<bool> DeleteStick(long id)
        {
            Stick stick = await this.DB.Sticks.FindAsync(id);
            if (stick == null)
            {
                return false;
            }
            this.DB.Sticks.Remove(stick);
            return await this.DB.SaveChangesAsync() > 0;
        }
    }

    public class OpResult
    {
        public long? Id { get; set; }
        public Boolean Success { get; set; }
    }
}
